package com.brother.service;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.brother.util.StringUtils;

public abstract class BaseService {
	
	public String escapeDBField(String v){
		if(v ==  null)
			return null;
		else
		 return	v.replaceAll("'", "\\\\'");
	}
	
	public void escapeAllFields(Object o){
		Class c = o.getClass();
		Field[] fs = c.getDeclaredFields();
		for(Field f : fs){
			//System.out.println(f.getType()+"  "+f.getType().getName()+"  "+String.class.getName());
			if(f.getType().getName().equals(String.class.getName())){
				try {
					Object value = null;
					Method m1 = c.getMethod("get"+ StringUtils.UpcaseFirst(f.getName()));
					if((value = m1.invoke(o)) != null){
						if(value.toString().indexOf("'") == -1){
							continue;
						}
						Method m2 = c.getMethod("set"+ StringUtils.UpcaseFirst(f.getName()), String.class);
						m2.invoke(o, value.toString().replaceAll("'", "\\\\'"));
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
